package com.study.jdbc.mydbutils;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

/**
* @Name: JDBCAssist
* @Description: 自定义JDBC框架工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 下午10:12:13 
* @Version: V1.0
 */
public class JDBCAssist {
	
	private DataSource dataSource ;

	public JDBCAssist(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public void update(String sql, Object ... params) {
		Connection conn = null ;
		PreparedStatement ps = null ;
		try {
			//获取数据库连接对象
			conn = dataSource.getConnection() ;
			//创建sql语句执行对象
			ps = conn.prepareStatement(sql) ;
			//预处理
			//获取sql语句中占位符的个数
			ParameterMetaData parameterMetaData = ps.getParameterMetaData() ;
			int parameterCount = parameterMetaData.getParameterCount() ;
			//判断sql语句中的占位符与实参个数是否一致
			if(parameterCount > 0) {
				if(params == null || params.length == 0) {
					throw new IllegalArgumentException("参数个数不一致！") ;
				}
				if(parameterCount != params.length) {
					throw new IllegalArgumentException("参数个数不一致！") ;
				}
				//参数个数一致，注入参数
				for (int i = 0; i < parameterCount; i++) {
					ps.setObject(i+1, params[i]) ;
				}
			}
			//执行sql语句
			ps.executeUpdate() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		} finally {
			//释放资源
			close(null, ps, conn) ;
		}
	}
	
	public Object query(String sql, ResultSetHandler rsh, Object ... params) {
		Connection conn = null ;
		PreparedStatement ps = null ;
		ResultSet rs = null ;
		Object result = null ;
		try {
			//获取数据库连接对象
			conn = dataSource.getConnection() ;
			//创建sql语句执行对象
			ps = conn.prepareStatement(sql) ;
			//sql语句预处理
			//获取sql语句占位符的个数
			ParameterMetaData parameterMetaData = ps.getParameterMetaData() ;
			int parameterCount = parameterMetaData.getParameterCount() ;
			//如果sql语句中有占位符，为其注入实参
			if(parameterCount > 0) {
				//比较占位符与实参的个数是否一致
				if(params == null || params.length == 0) {
					throw new IllegalArgumentException("参数个数不一致！") ;
				}
				if(parameterCount != params.length) {
					throw new IllegalArgumentException("参数个数不一致！") ;
				}
				//参数个数一致，注入参数
				for (int i = 0; i < parameterCount; i++) {
					ps.setObject(i+1, params[i]) ;
				}
			}
			//执行sql语句
			rs = ps.executeQuery() ;
			//返回执行结果
			result = rsh.handle(rs) ;
		} catch (Exception e) {
			e.printStackTrace() ;
		} finally {
			//释放资源
			close(rs, ps, conn) ;
		}
		return result ;
	}
	
	private void close(ResultSet rs, Statement s, Connection conn) {
		if(rs != null) {
			try {
				rs.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				rs = null ;
			}
		}
		if(s != null) {
			try {
				s.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				s = null ;
			}
		}
		if(conn != null) {
			try {
				conn.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				conn = null ;
			}
		}
	}
	

}
